package gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

/**
 *
 * @author Anders
 */
public class JGraphPanel extends JPanel{
    private Color foreground;
    private Color background;
    private double max;
    private double min;
    private int spacing;

    ArrayList<Double> speeds;

    public JGraphPanel(){
        speeds = new ArrayList<Double>();
        foreground = Color.WHITE;
        background = Color.BLACK;
        spacing = 10;
    }

    public void setSpacing(int spacing) {
        this.spacing = spacing;
    }

    @Override
    public void setForeground(Color color){
        foreground = color;
    }

    @Override
    public void setBackground(Color color){
        background = color;
    }

    /**
     *
     * @return The highest speed in the graph
     */
    public double getMax() {
        return max;
    }

    /**
     *
     * @return The lowest speed in the graph
     */
    public double getMin() {
        return min;
    }

    /**
     * Adds a speed to the graph
     *
     * @param speed - Current speed to be added to the graph
     */
    public synchronized void addSpeed(double speed){
        if (speed < 0)
            throw new IllegalArgumentException(
                    "Speed was negative, is your internet that bad?");
        speeds.add(speed);
        repaint();
    }

    public synchronized void setSpeeds(List<Double> speeds) {
    	this.speeds.clear();
    	this.speeds.addAll(speeds);
    	repaint();
    }
    
    private void adjustArraySize(){
        max = 0.0;
        min = Double.MAX_VALUE;
        while (speeds.size() > this.getWidth() / spacing){
            speeds.remove(0);
        }

        for (double speed : speeds){
            if (speed > max) max = speed;
            if (speed < min) min = speed;
        }
    }

    @Override
    public synchronized void paint(Graphics g2){
        Graphics2D g = (Graphics2D)g2;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //super.paint(g);
        adjustArraySize();
        if (speeds.size() < 2) return;

        g.setColor(background);
        g.fillRect(0, 0, getWidth(), getHeight());

        g.setColor(foreground);
        double lastSpeed = (speeds.get(0) - min + speeds.get(1) - min) / 2;
        int x = 0;
        for (double speed : speeds){
            double height = (double)getHeight();
            double currentSpeed = ((speed - min + lastSpeed) / 2);
            g.drawLine(x+spacing, (int)(((currentSpeed*height)/(max-min))), x, (int)(((lastSpeed*height)/(max-min))));
            lastSpeed = currentSpeed;
            x += spacing;
        }
    }
}
